package cn.easier.activity.console.service.impl;

import cn.easier.activity.console.repository.ActivityTemplateInfoRepository;
import cn.easier.activity.console.service.ActivityTemplateInfoService;
import cn.easier.activity.web.entity.ActivityTemplateInfo;
import cn.easier.club.base.dto.ResultInfo;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模板信息ServiceImpl
 */
@Service
@Transactional
public class ActivityTemplateInfoServiceImpl implements ActivityTemplateInfoService {

    @Autowired
    ActivityTemplateInfoRepository activityTemplateInfoRepository;

    @Override
    public Map<Integer, String> findAll() {
        List<ActivityTemplateInfo> all = activityTemplateInfoRepository.findAll();
        HashMap<Integer, String> map = new HashMap<>();
        for (ActivityTemplateInfo templateInfo : all) {
            map.put(templateInfo.getId(), templateInfo.getName());
        }
        return map;
    }

    @Override
    public ActivityTemplateInfo save(ActivityTemplateInfo activityTemplateInfo) {
        return activityTemplateInfoRepository.save(activityTemplateInfo);
    }

    @Override
    public ActivityTemplateInfo update(ActivityTemplateInfo activityTemplateInfo) {
        return activityTemplateInfoRepository.saveAndFlush(activityTemplateInfo);
    }

    @Override
    public ActivityTemplateInfo findOne(Integer id) {
        return activityTemplateInfoRepository.findOne(id);
    }

    @Override
    public ResultInfo findPage(String scienceLabelIds, String fromLabelIds, String themeLabelIds, String templateTypeIds, int pageNum, int pageSize) {
        Page<ActivityTemplateInfo> page = null;
        Pageable pageable = new PageRequest(pageNum, pageSize, new Sort(Sort.Direction.DESC, "id"));
        //如果没有参数，就视为查询所有
        if (Strings.isNullOrEmpty(scienceLabelIds) && Strings.isNullOrEmpty(fromLabelIds) && Strings.isNullOrEmpty(themeLabelIds) && Strings.isNullOrEmpty(templateTypeIds)) {
            page = activityTemplateInfoRepository.findAll(pageable);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                    String.valueOf(page.getTotalElements()), page.getContent());
        }

        //组织查询条件
        String[] params = null;
        if(!Strings.isNullOrEmpty(scienceLabelIds)){
            params = scienceLabelIds.split(",");
        }
        final String[] scienceLabelIdList = params;
        params = null;

        if(!Strings.isNullOrEmpty(fromLabelIds)){
            params = fromLabelIds.split(",");
        }
        final String[] fromLabelIdList = params;
        params = null;

        if(!Strings.isNullOrEmpty(themeLabelIds)){
            params = themeLabelIds.split(",");
        }
        final String[] themeLabelIdList = params;
        params = null;

        if(!Strings.isNullOrEmpty(templateTypeIds)){
            params = templateTypeIds.split(",");
        }
        final String[] templateTypeIdList = params;

        Specification<ActivityTemplateInfo> spec = new Specification<ActivityTemplateInfo>() {
            @Override
            public Predicate toPredicate(Root<ActivityTemplateInfo> root, CriteriaQuery<?> query,
                                         CriteriaBuilder cb) {
                //总的条件
                List<Predicate> predicateList = new ArrayList<>();
                //某标签类型条件
                List<Predicate> predicates = new ArrayList<>();
                //CriteriaBuilder组织条件的参数
                Predicate[] p = null;

                //适用环境条件，形如：where (scienceLabelId = a or scienceLabelId = b or ...) and ...
                if (scienceLabelIdList != null && scienceLabelIdList.length > 0) {
                    for (String scienceLabelId : scienceLabelIdList) {
                        predicates.add(cb.equal(root.get("scienceLabelId").as(Integer.class), Integer.valueOf(scienceLabelId)));
                    }
                    p = new Predicate[predicates.size()];
                    predicateList.add(cb.or(predicates.toArray(p)));
                    predicates = new ArrayList<>();
                }

                //活动形式条件，形如：where (fromLabelId = a or fromLabelId = b or ...) and ...
                if (fromLabelIdList != null && fromLabelIdList.length > 0) {
                    for (String fromLabelId : fromLabelIdList) {
                        predicates.add(cb.equal(root.get("fromLabelId").as(Integer.class), Integer.valueOf(fromLabelId)));
                    }
                    p = new Predicate[predicates.size()];
                    predicateList.add(cb.or(predicates.toArray(p)));
                    predicates = new ArrayList<>();
                }

                //活动主题条件，形如：where (themeLabelId = a or themeLabelId = b or ...) and ...
                if (themeLabelIdList != null && themeLabelIdList.length > 0) {
                    for (String themeLabelId : themeLabelIdList) {
                        predicates.add(cb.equal(root.get("themeLabelId").as(Integer.class), Integer.valueOf(themeLabelId)));
                    }
                    p = new Predicate[predicates.size()];
                    predicateList.add(cb.or(predicates.toArray(p)));
                    predicates = new ArrayList<>();
                }

                //模板类型条件，形如：where (templateTypeId = a or templateTypeId = b or ...) and ...
                if (templateTypeIdList != null && templateTypeIdList.length > 0) {
                    for (String templateTypeId : templateTypeIdList) {
                        predicates.add(cb.equal(root.get("templateTypeId").as(Integer.class), Integer.valueOf(templateTypeId)));
                    }
                    p = new Predicate[predicates.size()];
                    predicateList.add(cb.or(predicates.toArray(p)));
                }

                p = new Predicate[predicateList.size()];
                Predicate predicate = cb.and(predicateList.toArray(p));
                return predicate;
            }
        };

        //多条件查询
        page = activityTemplateInfoRepository.findAll(spec, pageable);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                String.valueOf(page.getTotalElements()), page.getContent());
    }

    @Override
    public List<ActivityTemplateInfo> getNewest(Integer top) {
        return activityTemplateInfoRepository.getNewestByTop(top);
    }

    @Override
    public String getActivityType(Integer templateId) {
        return activityTemplateInfoRepository.getActivityType(templateId);
    }

    @Override
    public boolean delete(Integer id) {
        int changeNum = activityTemplateInfoRepository.deleteFlag(id);
        if(changeNum > 0){
            return true;
        }
        return false;
    }
}
